<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/11
 * Time: 11:32
 */
namespace app\admin\controller;
use app\common\model\Purchase;
use Sunra\PhpSimple\HtmlDomParser;
use think\Cache;
use think\Db;
use think\Exception;
use wuliu\wuliu;

vendor('taobao.TopSdk');
class Goods extends Base{
private $tb_app_key = '24635648';
private $tb_app_secret = 'e3c6f335ca39011870018a730503de72';

    /**
     * 商品库 调用好单库
     */

    public function goods_list(){
        $item_cates = db('items_cate')->field('id,name,parent_id')->where('status',1)->select();
        $this->assign('item_cates',$item_cates);
        $gets['goods_cate'] = request()->get('goods_cate',0);//商品类型
        $gets['min_price'] = request()->get('min_price','');//最低价
        $gets['max_price'] = request()->get('max_price','');//最高价
        $gets['sales_volume'] = request()->get('sales_volume','');//最低销量
        $gets['sort'] = request()->get('sort',0);//排序
        $back = 50; //每页条数
        $nowPage = request()->get('nowpage',1); //页码
        $apikey = 'shen';
        $pages[0] = 1;
        $min_price= $gets['min_price'] == '' ? 0:$gets['min_price'];
        $max_price= $gets['max_price'] == '' ? 0:$gets['max_price'];
        $sales_volume= $gets['sales_volume'] == '' ? 0:$gets['sales_volume'];
        if ( $min_price != 0 && $max_price != 0){
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/price_min/".$min_price."/price_max/".$max_price."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }else if ($min_price == 0 && $max_price != 0){
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/price_max/".$max_price."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }else if ($min_price != 0 && $max_price == 0){
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/price_min/".$min_price."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }else{
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }
        $content_arr = Cache::get(md5($url));
        if (empty($content_arr)){
            $data = file_get_contents($url);
            $content_ori=strip_tags($data);
            $content_arr=json_decode($content_ori,true);
            Cache::set(md5($url),$content_arr,60);
        }
        foreach ($content_arr['data'] as $k=>$v){
            if ($v['itemsale'] >9999){
                $content_arr['data'][$k]['itemsale'] = round($v['itemsale'] / 10000,1).'万';
            }
            $content_arr['data'][$k]['couponurl'] = "https://uland.taobao.com/coupon/edetail?activityId=".$v['activityid']."&pid=".config('tk_pid')."&itemId=".$v['itemid']."&src=cd_cdll";
            $content_arr['data'][$k]['itempic_encode'] = urlencode($v['itempic']);
        }
        $this->assign('next_page',$content_arr['min_id']);
        $this->assign('gets',$gets);
        $this->assign('currpage',$nowPage);
        $this->assign('data',$content_arr['data']);
        return $this->fetch();

    }

    public function goods_new(){
        $page_param = input('param.');
        if (isset($page_param['page']) && $page_param['page'] > 0)
            unset($page_param['page']);
        $item_cates = db('items_cate')->field('id,name,parent_id')->where('status',1)->select(); //类目
        $this->assign('item_cates',$item_cates);
        $gets['goods_cate'] = request()->get('goods_cate',0);//商品类型
        $gets['min_price'] = request()->get('min_price','');//最低价
        $gets['max_price'] = request()->get('max_price','');//最高价
        $gets['sales_volume'] = request()->get('sales_volume','');//最低销量
        $gets['key_word'] = request()->get('key_word','');//关键词
        $gets['sort'] = request()->get('sort',0);//排序
        if ($gets['sort'] == 0){
            $sort = 'product_id desc';
        }elseif ($gets['sort'] == 1){
            $sort = 'itemendprice asc';
        }elseif ($gets['sort'] == 2){
            $sort = 'itemendprice desc';
        }elseif ($gets['sort'] == 3){
            $sort = 'couponmoney desc';
        }elseif ($gets['sort'] == 4){
            $sort = 'itemsale desc';
        }else{
            $sort = 'tkrates desc';
        }
        $min_price= $gets['min_price'] == '' ? 0:$gets['min_price'];
        $max_price= $gets['max_price'] == '' ? 0:$gets['max_price'];
        $sales_volume= $gets['sales_volume'] == '' ? 0:$gets['sales_volume'];
        if ( $min_price != 0 && $max_price != 0){
            $where['itemendprice'] = ['between',$min_price.','.$max_price];
        }elseif ($min_price == 0 && $max_price != 0){
            $where['itemendprice'] = ['lt',$max_price];
        }else if ($min_price != 0 && $max_price == 0){
            $where['itemendprice'] = ['gt',$min_price];
        }
        if ($gets['key_word'] != ''){
            $where['itemtitle'] = ['like','%'.$gets['key_word'].'%'];
        }
        $where['itemsale'] = ['gt',$sales_volume];
        if ($gets['goods_cate'] != 0){
            $where['fqcat'] = $gets['goods_cate'];
        }
        if ($gets['goods_cate'] == 0){
            $goods_list = Db::table('yf_items')->where($where)->order($sort)->paginate(45,false, ['query' => $page_param]);
        }else{
            $goods_list = Db::table('yf_items')->where($where)->order($sort)->paginate(45,false, ['query' => $page_param]);
        }

        //获取分页显示
        $goods_info = $goods_list->toArray();
        if (!empty($goods_info['data'])){
            foreach ($goods_info['data'] as $k=>$v){
                if ($v['itemsale'] >9999){
                    $goods_info['data'][$k]['itemsale'] = round($v['itemsale'] / 10000,1).'万';
                }
                $goods_info['data'][$k]['couponurl'] = "https://uland.taobao.com/coupon/edetail?activityId=".$v['activityid']."&itemId=".$v['itemid']."&src=cd_cdll";
                $goods_info['data'][$k]['itempic_encode'] = urlencode($v['itempic']);
            }
        }
        $page = $goods_list->render();
        $this->assign('gets',$gets);
        $this->assign('data',$goods_info['data']);
        $this->assign('page', $page);
        return $this->fetch();
    }



    public function ajax_goods(){
        $gets['goods_cate'] = request()->get('goods_cate',0);//商品类型
        $gets['min_price'] = request()->get('min_price','');//最低价
        $gets['max_price'] = request()->get('max_price','');//最高价
        $gets['sales_volume'] = request()->get('sales_volume','');//最低销量
        $gets['sort'] = request()->get('sort',0);//排序
        $back = 50; //每页条数
        $nowPage = request()->get('page',1); //页码
        $apikey = 'shen';
        $min_price= $gets['min_price'] == '' ? 0:$gets['min_price'];
        $max_price= $gets['max_price'] == '' ? 0:$gets['max_price'];
        $sales_volume= $gets['sales_volume'] == '' ? 0:$gets['sales_volume'];
        if ( $min_price != 0 && $max_price != 0){
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/price_min/".$min_price."/price_max/".$max_price."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }else if ($min_price == 0 && $max_price != 0){
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/price_max/".$max_price."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }else if ($min_price != 0 && $max_price == 0){
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/price_min/".$min_price."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }else{
            $url = "http://v2.api.haodanku.com/itemlist/apikey/".$apikey."/nav/3/cid/".$gets['goods_cate']."/back/".$back."/min_id/".$nowPage."/sale_min/".$sales_volume."/sort/".$gets['sort'];
        }
        $content_arr = Cache::get(md5($url));
        if (empty($content_arr)){
            $data = file_get_contents($url);
            $content_ori=strip_tags($data);
            $content_arr=json_decode($content_ori,true);
            Cache::set(md5($url),$content_arr);
        }
        $data = file_get_contents($url);
        $content_ori=strip_tags($data);
        $content_arr=json_decode($content_ori,true);
        foreach ($content_arr['data'] as $k=>$v){
            if ($v['itemsale'] >9999){
                $content_arr['data'][$k]['itemsale'] = round($v['itemsale'] / 10000,1).'万';
            }
        }
        return json($content_arr);
    }

    /**
     * 商品库
     */
    public function goods_list2(){
        $item_cates = db('items_cate')->field('id,name,parent_id')->where('status',1)->select();
        $this->assign('item_cates',$item_cates);
        $nowPage = request()->get('nowpage',1); //页码
        $gets['goods_cate'] = request()->get('goods_cate',0);//商品类型
        $item_name = '女装';
        foreach ($item_cates as $v){
            if ($v['id'] == $gets['goods_cate']){
                $item_name = $v['name'];
                break;
            }
        }
        $gets['min_price'] = request()->get('min_price','');//最低价
        $gets['max_price'] = request()->get('max_price','');//最高价
        $gets['commission'] = request()->get('commission','');//最低佣金比例
        $gets['sales_volume'] = request()->get('sales_volume','');//最低销量
        $limits = '35'; //默认
        $c = new \TopClient();
        $c->appkey = $this->tb_app_key;
        $c->secretKey = $this->tb_app_secret;
        $req = new \TbkItemGetRequest();
        $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
        $req->setQ($item_name);
        $req->setSort("tk_total_commi_des");
        $req->setIsOverseas("false");
        if (empty($gets['min_price']) || $gets['min_price'] == 0){
            $req->setStartPrice('0');
        }
        if (!empty($gets['min_price'])){
            $req->setStartPrice($gets['min_price']);
        }
        if ($gets['max_price'] >0){
            $req->setEndPrice($gets['max_price']);
        }
        if ($gets['commission'] >0){
            $req->setStartTkRate($gets['commission']);
        }
        if ($gets['commission'] >0){
            $req->setStartTkRate($gets['commission']);
        }
        $req->setPageNo($nowPage);
        $req->setPageSize($limits);
        $resp = $c->execute($req);
        $resp_list = $this->object_array($resp);
        $total = $resp_list['total_results'];
        foreach ($resp_list['results']['n_tbk_item'] as $k=>$v){
            if ($v['volume'] >9999){
                $resp_list['results']['n_tbk_item'][$k]['volume'] = round($v['volume'] / 10000,1).'万';
            }
        }
        $this->assign('gets',$gets);
        $this->assign('total',$total);
        $this->assign('currpage',$nowPage);
        $this->assign('data',$resp_list['results']['n_tbk_item']);
        return $this->fetch();
    }


    /**
     * 采购单
     */
    public function goods_purchase1(){
        $id = input('param.id',0);
        $user_type = input('param.user_type',0);
        if ($id !=0 && $user_type == 1){
            $url = 'https://detail.tmall.com/item.htm?id='.$id;
            $dom = HtmlDomParser::file_get_html($url);
            $start1=strstr($dom,"{\"api\"");
            $tp = strpos($start1,"</script>");
            $str = substr($start1,0,$tp);

            $str=iconv("GBK", "UTF-8", $str);
            $new_str = substr($str, 0, -11);
            $arr = json_decode($new_str,true);

            $url2="http://hws.m.taobao.com/cache/wdetail/5.0/?id=".$id;
            $content=file_get_contents($url2);
            $content_ori=strip_tags($content);
            $content_arr=json_decode($content_ori,true);
            $value = json_decode($content_arr['data']['apiStack'][0]['value'],true);
            foreach($arr['valItemInfo']['skuList'] as $k=>$v){
                $arr['valItemInfo']['skuList'][$k]['price'] = $value['data']['skuModel']['skus'][$v['skuId']]['priceUnits'][0]['price'];
            }
            $info= $arr['valItemInfo']['skuList'];
            $title = $arr['itemDO']['title'];
        }
        $this->assign('list',$info);
        $this->assign('url',$url);
        $this->assign('title',$title);
        return $this->fetch();
    }

    /**
     * 采购单
     */
    public function goods_purchase(){
        try{
            session('return_url',$_SERVER['HTTP_REFERER']);
            $id = input('param.id',0);
            $user_type = input('param.user_type','C');
            $item_cate = input('param.item_cate','');
            $activityid = input('param.activityid',''); //活动id 用于构造优惠券地址
            $couponmoney = input('param.couponmoney',''); //优惠券金额
            $info = $this->get_skuinfo($user_type,$id);
            /*$url="http://hws.m.taobao.com/cache/wdetail/5.0/?id=".$id;
            $content=file_get_contents($url);
            $content_ori=strip_tags($content);
            $content_arr=json_decode($content_ori,true);
            $values = json_decode($content_arr['data']['apiStack'][0]['value'],true);
            $title = $content_arr['data']['itemInfoModel']['title'];
            $data =[];
            if ($content_arr['data']['itemInfoModel']['sku']){
                $skuProps = $content_arr['data']['skuModel']['skuProps'];
                $sku_info = [];
                foreach ($skuProps as $k=>$v){
                    foreach ($v['values'] as $key=>$value){
                        $sku_info[$k]['propids'][]= $v['propId'].':'.$value['valueId'].';';
                        $sku_info[$k]['name'][]= $value['name'].' ';
                    }
                    $sku_ids[] = $sku_info[$k]['propids'];
                    $sku_name[] = $sku_info[$k]['name'];
                }
                $new_arr['ids'] = $this->zuhe($sku_ids);
                $new_arr['names'] = $this->zuhe($sku_name);
                foreach ($new_arr['ids'][0] as $t=>$vl){
                    $new_arr['ids'][0][$t] = trim($new_arr['ids'][0][$t],'/;/:');
                    $new_arr['names'][0][$t] = trim($new_arr['names'][0][$t],'/ /:');
                    $new_arr['skuid'][0][$t] = $content_arr['data']['skuModel']['ppathIdmap'][ $new_arr['ids'][0][$t]];
                    if (!isset($values['data']['skuModel']['skus'][$new_arr['skuid'][0][$t]]['priceUnits'][0]['price'])){
                        $new_arr['price'][0][$t] = 0;
                    }else{
                        $new_arr['price'][0][$t] = $values['data']['skuModel']['skus'][$new_arr['skuid'][0][$t]]['priceUnits'][0]['price'];
                    }
                }
                foreach ($new_arr['ids'][0] as $k=>$v){
                    $data[$k]['id'] = $v;
                    $data[$k]['name'] = $new_arr['names'][0][$k];
                    $data[$k]['sku_id'] = $new_arr['skuid'][0][$k];
                    $data[$k]['price'] = $new_arr['price'][0][$k];
                }
            }else{
                $data[0]['id'] = 0;
                $data[0]['name'] = '';
                $data[0]['sku_id'] =0;
                $data[0]['price'] = $values['data']['itemInfoModel']['priceUnits'][0]['price'];
            }*/

            if ($id !=0 && $user_type == 'B') {
                $goods_url = 'https://detail.tmall.com/item.htm?id=' . $id;
            }else{
                $goods_url = 'https://item.taobao.com/item.htm?id='.$id;
            }
            if ($item_cate != ''){
                $cate_name = Db::table('yf_items_cate')->field('name')->where(['id'=>$item_cate])->find();
            }else{
                $cate_name = '';
            }
            $shops = Db::table('yf_shop')->field('shop_name,id')->where(['status'=>1])->select();
            $this->assign('shops',$shops);
            $this->assign('cate_name',$cate_name['name']);
            $this->assign('cate_id',$item_cate);
            $this->assign('activityid',$activityid);
            $this->assign('couponmoney',$couponmoney);
            $this->assign('is_tmall',$user_type);
            $this->assign('list',$info['data']);
            $this->assign('url',$goods_url);
            $this->assign('title',$info['title']);
            $this->assign('id',$id);

            return $this->fetch();


        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 添加店铺商品
     */
    public function add_goods(){
        if ($this->request->isPost()){
            // 启动事务
            Db::startTrans();
            try{
                $data['tb_id'] = input('param.itemid',0); //淘宝商品id
                $data['goods_name'] = input('param.itemtitle','');//淘宝商品标题
                $data['original_img'] = input('param.itempic','');//商品图片
                $data['activity_type'] = input('param.activity_type/a','') == ''? '': implode(',',input('param.activity_type/a','')); //活动类型
                $data['cat_id'] = input('param.cat_id',0); //淘宝商品类别
                $data['sales_sum'] = input('param.itemsale',0); //销量
                $data['price'] = input('param.itemprice',0); //售价
                $data['store_count'] = input('param.store_count',0); //库存
                $data['sort'] = input('param.sort',0); //排序
                $data['shoptype'] = input('param.shoptype','C');//店铺类型 B天猫 C淘宝
                $data['is_on_sale'] = input('param.is_on_sale',0);//是否上架
                $data['tuijian'] = input('param.tuijian',0);//推荐
                $data['is_hot'] = input('param.is_hot',0);//是否热卖
                $data['shop_id'] = input('param.shop_id',0); //店铺
                if ($data['shop_id'] == 0 || $data['shop_id'] ==''){
                    throw new Exception('请选择店铺');
                }
                $num = Db::table('yf_goods')->where(['shop_id'=>$data['shop_id'],'tb_id'=>$data['tb_id']])->count();
                if ($num >0){
                    throw new Exception('该商品已添加过了，请勿重复添加');
                }
                if ($data['shoptype'] == 'B'){
                    $data['source_url'] = 'https://detail.tmall.com/item.htm?id='.$data['tb_id']; //商品链接
                }else{
                    $data['source_url'] = 'https://item.taobao.com/item.htm?id='.$data['tb_id']; //商品链接
                }
                $data['last_update'] = time(); //添加时间
                Db::table('yf_goods')->insert($data);
                Db::commit();
                return json(['code'=>200,'msg'=>'提交成功']);
            }catch (Exception $e){
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            $itemid = input('param.id',0); //商品id
            $iteminfo = Db::name('items')->field('a.*,b.name')->alias('a')->join('yf_items_cate b','a.fqcat=b.id','left')->where('a.itemid',$itemid)->find();
            $this->assign('data',$iteminfo);
            $items_cate = Db::name('items_cate')->field('id,name')->where('parent_id',0)->order('sort asc')->select();
            $this->assign('catetype',$items_cate);
            $shop_list =  Db::name('shop')->field('id,shop_name')->where(['status'=>1])->select();
            $this->assign('shops',$shop_list);
            return $this->fetch();
        }
    }

    //获取淘宝天猫的sku信息
    public function get_skuinfo($is_tmall='C',$itemid=0){
        if ($itemid == 0){
            throw new Exception('商品ID未传');
        }
        if ($is_tmall == 'B'){ //天猫
            $url = 'https://detail.tmall.com/item.htm?id='.$itemid;
            $dom = HtmlDomParser::file_get_html($url);
            $list['title'] = mb_convert_encoding($dom->find('title',0)->innertext(), "UTF-8", "GBK"); //标题
            $start1=strstr($dom,"{\"api\"");
            $tp = strpos($start1,"</script>");
            $str = substr($start1,0,$tp);
            $str=iconv("GBK", "UTF-8", $str);
            $new_str = substr($str, 0, -11);
            $arr = json_decode($new_str,true);
            if (!isset($arr['valItemInfo'])){
                $list['data'] = $this->get_datas($itemid,'B',1);
            }else{
                foreach ($arr['valItemInfo']['skuList'] as $k=>$v){
                    if ($arr['valItemInfo']['skuMap'][';'.$v['pvs'].';']['stock'] == 0){ //判断库存是否为空
                        continue;
                    }else{
                        $list['data'][] = $v; //将skuList保存到新数组中
                    }
                }
                $list_info = $this->get_datas($itemid,'B','');
                foreach ($list['data'] as $key=>$vv){
                    foreach ($list_info as $value){
                        if ($value['sku_id'] == $vv['skuId']){
                            $list['data'][$key]['price'] = $value['price'];
                            break;
                        }
                    }
                }
            }
        }else{
            $url = 'https://item.taobao.com/item.htm?id='.$itemid;
            $dom = HtmlDomParser::file_get_html($url);
            $list['title'] = mb_convert_encoding($dom->find('title',0)->innertext(), "UTF-8", "GBK");
            $start1=strstr($dom,"propertyMemoMap:");
            $tp = strpos($start1," Hub.config.set");
            $str = substr($start1,0,$tp);
            $str=iconv("GBK", "UTF-8", $str);
            $new_str = substr($str, 16, -14);
            $arr = json_decode($new_str,true);
            //获取sku名称
            $u = $dom->find(".tb-skin",0);
            $lins =[];
            $lin = [];
            foreach ($u->find('.J_Prop') as $key=>$elemt){
                if (mb_convert_encoding($elemt->find('dt',0)->innertext(), "UTF-8", "GBK") == '数量' || mb_convert_encoding($elemt->find('dt',0)->innertext(), "UTF-8", "GBK") == '花呗分期'){
                    continue;
                }
                foreach ($elemt->find('li') as $k=>$lit){
                    $name[$k]= mb_convert_encoding($lit->find('span',0)->innertext(), "UTF-8", "GBK").' ';
                    $sku_value[$k] =';'. mb_convert_encoding($lit->getAttribute('data-value'), "UTF-8", "GBK");
                }
                $lin[$key] = $name;//lin为规格名称的数组
                $lins[$key] = $sku_value;//lins为各sku的编码数组
                $name = [];
                $sku_value = [];
            }
            if (!empty($lins)){ //lins为各sku的编码数组
                $result = $this->zuhe($lins); //组合成各个sku
                foreach ($result[0] as $k=>$v){
                    $sku_list[$k] = $v.';';
                }
                $re = $this->zuhe($lin);
                $result_info['name'] =  $re[0]; //sku名称
                $result_info['pvs'] =  $sku_list; //sku pvs
                //组合成key为pvs value为相应sku的名称数组
                foreach ($sku_list as $k=>$v){
                    $data[$v] = $re[0][$k];
                }
                $list['data'] = $this->get_datas($itemid,'C');
                foreach ($list['data'] as $key=>$val){
                    $list['data'][$key]['names'] = $data[$val['pvs']];
                }
            }else{
                $list['data'] = $this->get_datas($itemid,'C',1);
            }
        }
        return $list;

    }

    public function get_datas($id,$is_tmall,$is_default=0){
        if ($is_tmall == 'B'){
            $url='https://mdskip.taobao.com/core/initItemDetail.htm?isUseInventoryCenter=false&cartEnable=true&service3C=false&isApparel=true&isSecKill=false&tmallBuySupport=true&isAreaSell=false&tryBeforeBuy=false&offlineShop=false&itemId='.$id.'&showShopProm=false&cachedTimestamp=1522308759411&isPurchaseMallPage=false&isRegionLevel=false&household=false&sellerPreview=false&queryMemberRight=true&addressLevel=2&isForbidBuyItem=false&callback=setMdskip&timestamp=1522315551231&isg=null&isg2=BHd3HcgO4fKkX2WfBKIeJNztBmsBlEv2mG-N6cklgMateJO60QmK7HU5XtgmkCMW&areaId=350200&cat_id=2&ref=https%3A%2F%2Flist.tmall.com%2Fsearch_product.htm%3Fq%3D%25D2%25C2%25B7%25FE%26type%3Dp%26spm%3Da220o.0.a2227oh.d100%26from%3D.detail.pc_1_searchbutton';
        }else{
            $url='https://detailskip.taobao.com/service/getData/1/p1/item/detail/sib.htm?itemId='.$id.'&modules=dynStock,qrcode,viewer,price,duty,xmpPromotion,delivery,upp,activity,fqg,zjys,amountRestriction,couponActivity,soldQuantity,originalPrice,tradeContract&callback=onSibRequestSuccess';
        }
        $url_refer = 'https://item.taobao.com';
        $ch = curl_init();
        //设置选项
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_REFERER, $url_refer);
        $header = array();
        $header[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
        $header[] = 'Accept-Language: zh-CN,zh;q=0.8';
        $header[] = 'Cache-Control: max-age=0';
        $header[] = 'Connection: keep-alive';
        $header[] = 'Cookie: uc3=nk2=0M56YNYN%2BA4%3D&id2=W8rr4uUwfV5Z&vt3=F8dAT%2B%2BMdeVt9sjBn%2Bk%3D&lg2=WqG3DMC9VAQiUQ%3D%3D; lgc=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; tracknick=%5Cu695A%5Cu5929%5Cu5B9D%5Cu9676; t=45643498fa8ff940a0534abf468c496b; _tb_token_=5touPdVYykOo; cookie2=9cc3ace3ba141f7e0e950da7b4782eae; tt=segmentfault.com; res=scroll%3A1349*6222-client%3A1349*667-offset%3A1349*6222-screen%3A1366*768; pnm_cku822=055UW5TcyMNYQwiAiwQRHhBfEF8QXtHcklnMWc%3D%7CUm5Ockt1T3BEf0N%2BSnJPciQ%3D%7CU2xMHDJ7G2AHYg8hAS8WKQcnCVU0Uj5ZJ11zJXM%3D%7CVGhXd1llXGJYZ1NoVGldZVhlUm9NeEd9SHFFfElyR35Be0N%2FR2k%2F%7CVWldfS0TMwY8ACAcKQkncVU4XSNKGn9AZE8BUDxQCW4PIXch%7CVmhIGCUFOBgkGiMXNwwzDDMTLxEqETELMAUlGSccJwc9AjdhNw%3D%3D%7CV25Tbk5zU2xMcEl1VWtTaUlwJg%3D%3D; cq=ccp%3D1; l=AikpB1ewOIvOADHsO87Aa9qtuduD9B0s; otherx=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; swfstore=142738; isg=4C03295B995DB1CB7ADB1CC702592A48';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //执行并获取HTML文档内容
        $data = curl_exec($ch);
        curl_close($ch);
        if ($is_tmall == 'B'){
            $searchString = "setMdskip (";
            $firstLength = strpos($data, $searchString);
            $length = $firstLength + strlen($searchString);
            $str = substr(substr($data, $length), 1,-1);
            $str = strip_tags($str);
            $str = mb_convert_encoding($str, "UTF-8", "GBK");
            $output_array = json_decode($str,true);
            if ($is_default == 1){
                $def = [];
                if (!empty($output_array['defaultModel']['itemPriceResultDO']['priceInfo']['def']['promotionList'])){
                    $def[0]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo']['def']['promotionList'][0]['price'];
                    $def[0]['names'] = '默认';
                    $def[0]['pvs'] = '';
                }else{
                    $def[0]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo']['def']['price'];
                    $def[0]['names'] = '默认';
                    $def[0]['pvs'] = '';
                }
                return $def;
            }
            $key_list = array_keys($output_array['defaultModel']['itemPriceResultDO']['priceInfo']); //获取键值数组
            foreach ($key_list as $k=>$v){
                $arr[$k]['sku_id'] = $v;
                if (!empty($output_array['defaultModel']['itemPriceResultDO']['priceInfo'][$v]['promotionList'])){
                    $arr[$k]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo'][$v]['promotionList'][0]['price'];
                }else{
                    $arr[$k]['price'] = $output_array['defaultModel']['itemPriceResultDO']['priceInfo'][$v]['price'];
                }
            }
        }else{
            $searchString = "onSibRequestSuccess(";
            $firstLength = strpos($data, $searchString);
            $length = $firstLength + strlen($searchString);
            $str = substr(substr($data, $length), 0,-2);
            $str = strip_tags($str);
            $str = mb_convert_encoding($str, "UTF-8", "GBK");
            $output_array = json_decode($str,true);
            if ($is_default==1){
                if (!empty($output_array['data']['promotion']['promoData'])){
                    $def[0]['price'] = $output_array['data']['promotion']['promoData']['def'][0]['price'];
                    $def[0]['names'] = '默认';
                    $def[0]['pvs'] = '';
                }else{
                    $def[0]['price'] = $output_array['data']['originalPrice']['def']['price'];
                    $def[0]['names'] = '默认';
                    $def[0]['pvs'] = '';
                }
                return $def;
            }
            $pvs = []; //获取有货的pvs
            foreach ($output_array['data']['dynStock']['sku'] as $k=>$v){
                if ($v['stock'] == 0){
                    continue;
                }else{
                    $pvs[]=$k;
                }
            }
            $arr = [];
            if (empty($output_array['data']['promotion']['promoData'])){
                foreach ($pvs as $key=>$value){
                    $arr[$key]['pvs'] = $value;
                    $arr[$key]['price'] = $output_array['data']['originalPrice'][$value]['price'];
                }
            }else{
                foreach ($pvs as $key=>$value){
                    $arr[$key]['pvs'] = $value;
                    if (isset($output_array['data']['promotion']['promoData'][$value])){
                        $arr[$key]['price'] = $output_array['data']['promotion']['promoData'][$value][0]['price'];
                    }else{
                        $arr[$key]['price'] = $output_array['data']['originalPrice'][$value]['price'];
                    }

                }
            }
        }
        return $arr;
    }
    /**
     * 采购单提交  备用
     */
    public function purchase_save_backup(){
        if (request()->isPost()){
            // 启动事务
            Db::startTrans();
            try{
                $title = input('param.title','');//淘宝商品标题
                $url = input('param.url','');//淘宝商品链接
                $id = input('param.tb_id',0); //淘宝商品id
                $cat_id = input('param.cat_id',0); //淘宝商品类别
                $activityid = input('param.activityid',''); //该商品的活动id 用于构造优惠券地址
                $couponmoney = input('param.couponmoney',0); //优惠券金额
                $is_tmall = input('param.is_tmall',0);//是否是天猫 0不是 1是
                $total = input('param.total',0);//是否是天猫 0不是 1是
                $shop_id = input('param.shop',0); //收货的店铺
                if ($shop_id == 0 || $shop_id ==''){
                    throw new Exception('请选择收货店铺');
                }
                $sku_name = input('param.sku_name/a','');
                $price = input('param.price/a','');
                $num = input('param.num/a','');
                $get_url="http://hws.m.taobao.com/cache/wdetail/5.0/?id=".$id;
                $content=file_get_contents($get_url);
                $content_ori=strip_tags($content);
                $content_arr=json_decode($content_ori,true);
                $img_url = $content_arr['data']['itemInfoModel']['picsPath'][0];
                $data = [];
                $all_num = 0;
                foreach ($num as $k=>$v){
                    if (!empty($v)){
                        $key[] = $k; //获取需要采购的sku
                        $all_num +=$v; //获取该商品的总需求数
                    }
                }
                $purchase = new Purchase();
                $couponurl = 'https://uland.taobao.com/coupon/edetail?activityId='.$activityid.'&pid='.config('tk_pid').'&itemId='.$id.'&src=cd_cdll';
                $purchase_id = $purchase->purchase_add($title,$all_num,$all_num,0,$shop_id,$total,$id,$is_tmall,$url,$img_url,$all_num,$cat_id,$couponurl,min($price)-$couponmoney);
                if (!$purchase_id){
                    throw new Exception($purchase->getError());
                }
                if (!$purchase_id){
                    throw new Exception('采购需求创建失败');
                }
                /*以前的写法
                foreach ($key as $t=>$value){
                    if ($num[$value] == 1){
                        $one_data['number'] = 1;
                        $one_data['tb_id'] = $id;//该商品在淘宝上的id
                        $one_data['spec_name'] = $sku_name[$value]; //规格名称
                        $one_data['status'] = 0; //状态 0 发布采购需求
                        $one_data['money'] = 1;
                        $one_data['tb_skuid'] = $sku_id[$value]; //该规格在淘宝上的skuid
                        $one_data['purchase_id'] = $purchase_id; //采购id
                        $one_data['create_time'] = time(); //发布需求时间
                        Db::table('yf_demand')->insert($one_data);
                    }else{
                        for ($i=0;$i<$num[$value];$i++){
                            $data[$i]['number'] = 1; //该规格采购的数量
                            $data[$i]['tb_id'] = $id; //该商品在淘宝上的id
                            $data[$i]['spec_name'] = $sku_name[$value]; //规格名称
                            $data[$i]['status'] = 0; //状态 0 发布采购需求
                            $data[$i]['money'] = $price[$value]; //采购该规格的价钱
                            $data[$i]['tb_skuid'] = $sku_id[$value]; //该规格在淘宝上的skuid
                            $data[$i]['purchase_id'] = $purchase_id; //采购id
                            $data[$i]['create_time'] = time(); //发布需求时间
                        }
                        Db::table('yf_demand')->insertAll($data);
                    }

                }*/
                foreach ($key as $t=>$value){
                    $one_data['purchase_id'] = $purchase_id; //采购id
                    $one_data['spec_name'] = $sku_name[$value]; //规格名称
                    $one_data['number'] = $num[$value];
                    $one_data['price'] = $price[$value] - $couponmoney;
                    $one_data['residual_task'] = $num[$value];
                    $one_data['waiting_storage'] = 0;
                    $one_data['already_storage'] = 0;
                    Db::table('yf_demands')->insert($one_data);
                }
                Db::commit();
                return json(['code'=>200,'msg'=>'提交成功']);
            }catch (Exception $e){
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            return json(['code'=>0,'msg'=>'提交错误']);
        }
    }

    /**
     * 采购单提交  备用
     */
    public function purchase_save(){
        if (request()->isPost()){
            // 启动事务
            Db::startTrans();
            try{
                $title = input('param.title','');//淘宝商品标题
                $url = input('param.url','');//淘宝商品链接
                $id = input('param.tb_id',0); //淘宝商品id
                $cat_id = input('param.cat_id',0); //淘宝商品类别
                $activityid = input('param.activityid',''); //该商品的活动id 用于构造优惠券地址
                $couponmoney = input('param.couponmoney',0); //优惠券金额
                $is_tmall = input('param.is_tmall',0);//是否是天猫 0不是 1是
                $total = input('param.total',0);//是否是天猫 0不是 1是
                $shop_id = input('param.shop',0); //收货的店铺
                if ($shop_id == 0 || $shop_id ==''){
                    throw new Exception('请选择收货店铺');
                }
                $num = Db::table('yf_goods')->where(['shop_id'=>$shop_id,'tb_id'=>$id])->count();
                if ($num >0){
                    throw new Exception('该商品已添加过了，请勿重复添加');
                }
                $shoptype = 'C';
                if ($is_tmall == 'B'){
                    $shoptype = 'B';
                    $source_url = 'https://detail.tmall.com/item.htm?id='.$id;
                }else{
                    $source_url = 'https://item.taobao.com/item.htm?id='.$id;
                }
                $sku_name = input('param.sku_name/a','');
                $price = input('param.price/a','');
                $num = input('param.num/a','');
                $dom = HtmlDomParser::file_get_html($url);
                $img_url = 'http:'.mb_convert_encoding($dom->find('#J_ImgBooth',0)->src, "UTF-8", "GBK");//商品图片
                $price_min = min($price);
                Db::table('yf_goods')->insert(['cat_id'=>$cat_id,'goods_name'=>$title,'price'=>$price_min,'original_img'=>$img_url,'is_new'=>1,'last_update'=>time(),'shop_id'=>$shop_id,'tb_id'=>$id,'store_count'=>20,'shoptype'=>$shoptype,'source_url'=>$source_url]);
                Db::commit();
                return json(['code'=>200,'msg'=>'提交成功']);
            }catch (Exception $e){
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,'msg'=>$e->getMessage()]);
            }
        }else{
            return json(['code'=>0,'msg'=>'提交错误']);
        }
    }


    function zuhe($arr){
        if(count($arr) >= 2){
            $tmparr = array();
            $arr1 = array_shift($arr);
            $arr2 = array_shift($arr);
            foreach($arr1 as $k1 => $v1){
                foreach($arr2 as $k2 => $v2){
                    $tmparr[] = $v1.$v2;
                }
            }
            array_unshift($arr, $tmparr);
            $arr = $this->zuhe($arr);
        }else{
            return $arr;
        }
        return $arr;
    }

    /**
     * 采购中列表
     */

    public function purchase_list(){
        $list_info = db('purchase')->field('a.*,b.shop_name')->alias('a')->join('yf_shop b','a.shop=b.id','LEFT')->where('a.already_storage','exp',"!= `a`.`goods_num`")->order('id desc')->paginate(20);
        // 获取分页显示
        $page = $list_info->render();
        $listInfo = $list_info->toArray();
        // 模板变量赋值
        $this->assign('list', $listInfo['data']);
        $this->assign('page', $page);
        $this->assign('total', $listInfo['total']);
        return $this->fetch();
    }


    /**
     * 采购中详情
     */

    public function purchase_detail(){
        $purchase_id = input('param.id',0);
        if ($purchase_id == 0){
            $this->error('采购单id无效');
        }
        $list_info = db('purchase')->alias('a')->field('a.*,b.shop_name')->join('yf_shop b','a.shop=b.id','LEFT')->where(['a.id'=>$purchase_id])->find();
//        $demand = Db::table('yf_demand')->field('*,count(DISTINCT id) num,count(status=1 or null) wait_num,count(status=2 or null) already_num')->where(['purchase_id'=>$purchase_id])->group('tb_skuid')->select();
       $demands = Db::table('yf_demands')->where(['purchase_id'=>$purchase_id])->select();
        foreach ($demands as $k=>$v){
            $data[$k]['info'] = $v;
            $data[$k]['list'] = db('member_task')->where(['purchase_id'=>$purchase_id,'demand_id'=>$v['id']])->select();
        }
        // 模板变量赋值
        $this->assign('list_info', $list_info);
        $this->assign('data', $data);
        return $this->fetch();
    }




    /**
     * 已完成
     */
    public function goods_finish(){
        $list = Db::table('yf_purchase')->alias('a')->field('a.*,b.shop_name')->join('yf_shop b','a.shop=b.id','LEFT')->where('a.already_storage','exp',"= `a`.`goods_num`")->order('a.id desc')->paginate(20);
        $page = $list->render();
        $list_info = $list->toArray();
        $this->assign('total',$list_info['total']);
        $this->assign('page',$page);
        $this->assign('list',$list_info['data']);
        return $this->fetch();
    }

    /**
     * 获取物流信息
     */
    public function ajax_getwuliu(){
        $number = input('param.number',0); //物流号
        $id = input('param.id',0); //任务id
        if ($id == 0 ){
            return json(['code'=>0,'msg'=>'订单号不能为空']);
        }
        $demand_info = db('member_task')->where('id',$id)->find();
        if (empty($demand_info)){
            return json(['code'=>0,'data'=>'','msg'=>'暂无该条任务的记录']);
        }
        if (empty($demand_info['courier_sn'])){
            return json(['code'=>0,'data'=>'','msg'=>'该条任务记录无物流单号']);
        }
        if (empty($demand_info['wuliu_com'])){
            return json(['code'=>0,'data'=>'','msg'=>'该条任务记录无物流公司编号']);
        }
        $data = Cache::get('wuliu'.$demand_info['courier_sn']);
        if (empty($data)) {
            $requestData = "{'OrderCode':'','ShipperCode':'" . $demand_info['wuliu_com'] . "','LogisticCode':'" . $demand_info['courier_sn'] . "'}";
            $datas = array(
                'EBusinessID' => config('wuliu.appid'),
                'RequestType' => '1002',
                'RequestData' => urlencode($requestData),
                'DataType' => '2',
            );
            $datas['DataSign'] = urlencode(base64_encode(md5($requestData . config('wuliu.key'))));
            $result = curl_request(config('wuliu.req_url'), $datas);
            if ($result['Success'] == true) {
                $task_info['state'] = $result['State'];
                $task_info['list'] = $result['Traces'];
                $task_info['success'] = $result['Success'];
                cache('wuliu' . $demand_info['courier_sn'], $task_info);
                return json(['code'=>200,'data'=>$task_info,'msg'=>'SUCCESS']);
            } else {
                $task_info['success'] = $result['Success'];
                $task_info['state'] = '';
                $task_info['list'] = [];
                return json(['code'=>0,'data'=>$task_info,'msg'=>'该订单暂无物流新信息']);
            }
        }else{
            return json(['code'=>200,'data'=>$data,'msg'=>'SUCCESS']);
        }
    }

    /**
     * 空操作
     */
    public function _empty(){
        $this->redirect('admin/login');
    }

    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        }
        if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }
}